package io.qar.service.impl;

import io.qar.categories.dao.CategoriesDao;
import io.qar.categories.dto.CategoriesDTO;
import io.qar.categories.entity.CategoriesEntity;
import io.qar.categories.service.CategoriesService;
import io.qar.commons.mybatis.utils.Page;
import io.qar.commons.tools.utils.ConvertUtils;
import io.qar.commons.tools.validator.ValidatorUtils;
import io.qar.service.PageSerice;
import io.qar.utils.TreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PageSericeImpl implements PageSerice {
    @Autowired
    private CategoriesDao categoryDao;
    @Autowired
    private CategoriesService categoryService;


    @Override
    public Page<CategoriesDTO> selectPageByName(String name, Integer page, Integer limit) {
        // 计算偏移量，确保curPage有效
        if (page <= 0) {
            throw new IllegalArgumentException("页码必须大于0");
        }
        int offset = (page - 1) * limit;
        List<CategoriesEntity> categoriesEntities = categoryDao.selectPageByName(name, offset, limit);
        Long total = categoryService.selectCount();
        List<CategoriesDTO> categoriesDTOS = TreeUtils.build(ConvertUtils.sourceToTarget(categoriesEntities, CategoriesDTO.class));
        Page<CategoriesDTO> categoriesDTOPage = new Page<CategoriesDTO>(categoriesDTOS, total, page, limit);
        ValidatorUtils.validateEntity(categoriesDTOPage);
        return categoriesDTOPage;
    }
}
